package org.jeecg.modules.zhima.portal.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.jeecg.modules.zhima.base.util.RedisKeyUtil;
import org.jeecg.modules.zhima.base.util.RedisUtil;
import org.jeecg.modules.zhima.center.entity.PmsProductCategory;
import org.jeecg.modules.zhima.center.service.IPmsProductCategoryService;
import org.jeecg.modules.zhima.portal.domain.Category;
import org.jeecg.modules.zhima.portal.service.ICategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private IPmsProductCategoryService productCategoryService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<Category> listCategory(Integer parentId) {
        String key = redisUtil.getKeyWithColumn(RedisKeyUtil.CATEGORY_LIST, String.valueOf(parentId));
        if (redisUtil.hasKey(key)){
            return (List<Category>)redisUtil.get(key);
        }
        List<Category> categoryList = new ArrayList<>();
        List<PmsProductCategory> productCategoryList = productCategoryService.listByParentId(parentId);
        if (CollectionUtils.isNotEmpty(productCategoryList)){
            for (int i = 0; i < productCategoryList.size(); i++) {
                Category category = new Category();
                PmsProductCategory productCategory = productCategoryList.get(i);
                BeanUtils.copyProperties(productCategory, category);
                category.setSubCategoryList(productCategoryService.listByParentId(category.getId()));
                categoryList.add(category);
            }
        }
        redisUtil.set(key, categoryList);
        return categoryList;
    }

    @Override
    public Category currentCategory(Integer id) {
        Category category = new Category();
        PmsProductCategory productCategory = productCategoryService.getById(id);
        BeanUtils.copyProperties(productCategory, category);
        category.setSubCategoryList(productCategoryService.listByParentId(category.getId()));
        return category;
    }

}
